package cn.kgc.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * WebSocket  服务端的初始化器  指定使用Handler  处理 WebSocket 请求
 */

public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        socketChannel.pipeline()
                //处理编码和解码
                .addLast(new HttpServerCodec())
                //防止一次写入大数据快  造成内存溢出
                .addLast(new ChunkedWriteHandler())
                //可以将多个http请求合并成一个完整的http 请求 最大是64KB
                .addLast(new HttpObjectAggregator(64 * 1024))
                //处理WebSocket请求 Websocket请求路径是以/ws开头
                .addLast(new WebSocketServerProtocolHandler("/ws"))
                //心跳检测  60秒内没有读写操作  就会触发心跳检测机制
                .addLast(new IdleStateHandler(60,60,150))
                //自定义Handler接收客户端发送的消息  并且给客户返回消息
                .addLast(new ChatHandler())
                //心跳检测Handler
                .addLast(new HearBeatHandler());
    }
}
